<?php
class Models_Login extends Zend_Db_Table_Abstract{
    protected $_name="staff";
    protected $_primary="StaffID";

    public function check_login($user,$pass){
        if($user != "" && $pass != ""){
            $db = Zend_Registry::get('dbAdapter');  
            $authAdapter = new Zend_Auth_Adapter_DbTable($db);
            $authAdapter->setTableName('staff')  
                        ->setIdentityColumn('Username')  
                        ->setCredentialColumn('Password') ;
            $authAdapter->setIdentity($user)  
                        ->setCredential($pass);             
            $auth = Zend_Auth::getInstance();
            try {
                $result = $auth->authenticate($authAdapter);
            } catch (Exception $e) {
                echo $e->getMessage();
            }
            if ($result->isValid()) {
                $storage = $auth->getStorage();
                $storage->write($authAdapter->getResultRowObject(null,'Password'));
                $this->setSession($auth->getIdentity()->StaffID);
                return TRUE;
            }else{
                return FALSE;
            }
        }else{
            return FALSE;
        }
    }
    public function logout(){
        Zend_Session::destroy();
        // Zend_Auth::getInstance()->clearIdentity();
    }
    public function setSession($StaffID){
        $session = new Clound_Session();
        $session->set('Staff',$this->getAllStaff());
        $session->set('Unit',$this->getAllUnit());
		//$session->set('Permission',$this->getAllPermission($StaffID));
    }

    private function getAllStaff(){
        $query = "SELECT StaffID,UnitID,PositionCode,Name FROM $this->_name";
        $query .= " Where Status = '1'";
        $query .= " Order by UnitID,StaffID";
        try {
            $rows = $this->getAdapter()->fetchAll($query);
        } catch (Exception $e) {
            echo $e->getMessage();
        }
        return $rows;
    }

    private function getAllUnit(){
        $query = "SELECT UnitID,UnitParent,Name FROM unit";
        $query .= " Where Status = '1'";
        $query .= " Order by UnitID";
        try {
            $rows = $this->getAdapter()->fetchAll($query);
        } catch (Exception $e) {
            echo $e->getMessage();
        }
        return $rows;
    }
	/*
    private function getAllPermission($StaffID){
        $query = "SELECT Roles FROM permission";
        $query .= " Where StaffID = '".$StaffID."'";
        try {
            $rows = $this->getAdapter()->fetchAll($query);
        } catch (Exception $e) {
            echo $e->getMessage();
        }
        return $rows;
    }
	*/
}